#!/usr/bin/env python3
# Copyright © 2018 The Lingmo Music Developers
#
# Lingmo Music is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Lingmo Music is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with Lingmo Music; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# The Lingmo Music authors hereby grant permission for non-GPL compatible
# GStreamer plugins to be used and distributed together with GStreamer
# and Lingmo Music.  This permission is above and beyond the permissions
# granted by the GPL license by which Lingmo Music is covered.  If you
# modify this code, you may extend this exception to your version of the
# code, but you are not obligated to do so.  If you do not wish to do so,
# delete this exception statement from your version.

import gettext
import locale
import os
import signal
import sys

_LOCAL = @local_build@

if _LOCAL:
    # In the local use case, use lingmomusic module from the sourcetree
    sys.path.insert(1, '@pythondir@')

    # In the local use case the installed schemas go in <builddir>/data
    os.environ["XDG_DATA_DIRS"] = '@schemasdir@:' + os.environ.get("XDG_DATA_DIRS", "")

import gi

gi.require_version("Adw", "1")
gi.require_version('Gtk', '4.0')
gi.require_version('GIRepository', '2.0')
gi.require_version('Gst', '1.0')
from gi.repository import Adw, GIRepository, Gio, Gtk, Gst

Gst.init(None)
Adw.init()

LOCALE_DIR = '@localedir@'
PKGDATA_DIR = '@pkgdatadir@'
VERSION = '@version@'

def set_exception_hook():
    """Configures sys.excepthook to enforce Gtk application exiting."""

    def new_hook(etype, evalue, etb):
        old_hook(etype, evalue, etb)
        while Gtk.main_level():
            Gtk.main_quit()
        sys.exit()

    old_hook = sys.excepthook
    sys.excepthook = new_hook

def set_internationalization():
    """Sets application internationalization."""
    try:
        locale.bindtextdomain('@application_id@', LOCALE_DIR)
        locale.textdomain('@application_id@')
    except AttributeError as e:
        # Python built without gettext support does not have
        # bindtextdomain() and textdomain().
        print(
            "Could not bind the gettext translation domain. Some"
            " translations will not work. Error:\n{}".format(e))

    gettext.bindtextdomain('@application_id@', LOCALE_DIR)
    gettext.textdomain('@application_id@')


def set_resources():
    """Sets application ressource file."""
    resource = Gio.resource_load(
        os.path.join(PKGDATA_DIR, '@rdnn_name@.gresource'))
    Gio.Resource._register(resource)  # nopep8


def run_application():
    """Runs Lingmo Music application and returns its exit code."""
    from lingmomusic.application import Application

    app = Application('@application_id@', VERSION)
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    return app.run(sys.argv)


def main():
    """Sets environment and runs Lingmo Music."""
    # set_exception_hook()
    set_internationalization()
    set_resources()
    return run_application()

if __name__ == '__main__':
    if _LOCAL:
        print('Running from source tree, using local files.')
    sys.exit(main())
